#include<stdio.h>
#include<stdlib.h>
#include"bmpfile.h"

typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;

//内部函数实现
static int ALIGN(int x, int y) {
	//y must be a power of 2.
	return (x + y - 1) & ~(y - 1);
}

//使结构体按1字节方式对齐
#pragma pack(1)
typedef struct {
	uint16_t bfType;
	uint32_t bfSize;
	uint16_t bfReserved1;
	uint16_t bfReserved2;
	uint32_t bfOffBits;
	uint32_t biSize;
	uint32_t biWidth;
	uint32_t biHeight;
	uint16_t biPlanes;
	uint16_t biBitCount;
	uint32_t biCompression;
	uint32_t biSizeImage;
	uint32_t biXPelsPerMeter;
	uint32_t biYPelsPerMeter;
	uint32_t biClrUsed;
	uint32_t biClrImportant;
}BMPFILEHEADER;
#pragma pack() 

static void putpixel(int x, int y, uint8_t r, uint8_t g, uint8_t b)
{
}

//dui qi
#define ALIGN(a, b) (((a) + ((b) - 1)) & ~((b) - 1))

int main(void)
{
	FILE *fp = fopen("bmptest.bmp", "rb");
	if (fp)
	{
		BMPFILEHEADER header = {};
		uint8_t *rgb = NULL;
		int x, y, stride;

		fread(&header, 1, sizeof(header), fp);
		printf("header.biwidth   : % d\n", header.biWidth   );
		printf("header.biHeight  : % d\n", header.biHeight  );
		printf("header.biBitCount: % d\n", header.biBitCount);
		printf("header.bfOffBits : % d\n", header.bfOffBits);
		printf("header.biSizeImage : % d\n", header.biSizeImage);

		rgb = malloc(header.biSizeImage);
		if (rgb)
		{
			fread(rgb, 1, header.biSizeImage, fp);
			stride = header.biWidth * header.biBitCount / 8;
			//mai bu
			stride = ALIGN(stride, 4);
			for (y = 0; y < header.biHeight; y++)
			{
				for (x = 0; x < header.biWidth; x++)
				{
					putpixel(x, y, rgb[2], rgb[1], rgb[0]);
					rgb += 3;
				}
				rgb += stride - header.biWidth * header.biBitCount / 8;
			}
		}
		fclose(fp);
	}
	return 0;
}
